<template>
  <div class="admin-countries">
    <div class="header flex justify-between items-center mb-4">
      <el-button type="primary" @click="dialogVisible = true">
        创建标准列
      </el-button>
    </div>
    <!-- 搜索表单 -->
    <el-form
      ref="searchFormRef"
      :model="searchForm"
      inline
      class="search-form mb-4"
    >
      <el-form-item label="关键词" prop="keyword">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入关键词"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="onlyEnabled">
        <el-select
          v-model="searchForm.onlyEnabled"
          placeholder="请选择"
          clearable
          class="!w-[150px]"
        >
          <el-option label="启用" :value="true" />
          <el-option label="禁用" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 国家配置列表 -->
    <el-table
      :data="tableData"
      stripe
      border
      style="width: 100%"
      show-overflow-tooltip
    >
      <el-table-column
        prop="sortOrder"
        label="序号"
        align="center"
        width="80"
      />
      <el-table-column prop="id" label="ID" align="center" width="80" />
      <el-table-column prop="columnType" align="center" label="列类型" />
      <el-table-column prop="standardName" align="center" label="标准列名" />
      <el-table-column label="启用状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.enabled ? 'success' : 'info'">
            {{ scope.row.enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" align="center" label="描述" />
      <el-table-column
        prop="mappingCount"
        align="center"
        label="关联映射数量"
        width="110"
      />
      <el-table-column
        prop="enabledMappingCount"
        align="center"
        label="启用映射数量"
        width="110"
      />
      <el-table-column prop="createTime" align="center" label="创建时间" />
      <el-table-column prop="updateTime" align="center" label="更新时间" />
      <el-table-column label="操作" align="center" fixed="right" width="260">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            link
            @click="editStandardColumn(scope.row)"
            >编辑</el-button
          >
          <el-button type="primary" size="small" link @click="setMap(scope.row)"
            >设置标准列映射关系</el-button
          >
          <el-button
            type="danger"
            size="small"
            link
            @click="deleteCountry(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      class="mt-4"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      :page-sizes="[20, 40, 60]"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 新增/编辑国家对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑列' : '新增列'"
      width="500px"
      @close="close"
    >
      <el-form
        ref="countryFormRef"
        :model="countryForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item v-show="!isEdit" label="列类型" prop="columnType">
          <el-input
            v-model="countryForm.columnType"
            placeholder="请输入列类型"
          />
        </el-form-item>
        <el-form-item label="标准列名" prop="standardName">
          <el-input
            v-model="countryForm.standardName"
            placeholder="请输入标准列名"
          />
        </el-form-item>
        <el-form-item label="排序序号" prop="sortOrder">
          <el-input-number
            v-model="countryForm.sortOrder"
            placeholder="请输入排序序号"
            :step="1"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="启用状态" prop="enabled">
          <el-switch
            v-model="countryForm.enabled"
            :active-value="true"
            :inactive-value="false"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="countryForm.description"
            placeholder="请输入描述"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoad" @click="submitCountry"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <MapIdsDialog ref="mapIdsDialogRef" @refresh="onSearch" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import {
  getAllColumnStandards,
  deleteColumnwStandards,
  createColumnStandards,
  updateColumnStandards,
  getMappingIds
} from "@/api/adminStandardColumnApi";
import MapIdsDialog from "./components/MapIdsDialog.vue";
const mapIdsDialogRef = ref();
// 搜索表单数据
const searchForm = reactive({
  keyword: "",
  onlyEnabled: true
});
const searchFormRef = ref();

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 表格数据
const tableData = ref<any[]>([]);

// 获取所有国家配置数据
const fetchCountries = async () => {
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    };
    const { success, data, message } = await getAllColumnStandards(params);
    if (success) {
      const { records, total, size, current } = data;
      // 安字段sortOrder从小到大排序;
      tableData.value = records.sort((a, b) => a.sortOrder - b.sortOrder);
      pagination.total = total;
      pagination.pageSize = size;
      pagination.currentPage = current;
    } else {
      ElMessage.error(message);
    }
  } catch (error) {
    console.log(error);
  }
};
const setMap = async (row: any) => {
  try {
    const { data } = await getMappingIds(row.id);
    mapIdsDialogRef.value.open(row.id, data);
  } catch (error) {
    console.log(error);
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchCountries();
};

const onReset = () => {
  searchForm.keyword = "";
  searchForm.onlyEnabled = true;
  pagination.currentPage = 1;
  fetchCountries();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  fetchCountries();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchCountries();
};

// 新增/编辑对话框相关
const dialogVisible = ref(false);
type FormType = {
  id?: number | string;
  columnType?: string;
  standardName?: string;
  description?: string;
  sortOrder?: number;
  enabled?: boolean;
};
const countryForm = ref<FormType>({
  columnType: "",
  standardName: "",
  description: "",
  sortOrder: 0,
  enabled: true
});
const countryFormRef = ref<FormInstance>();

const rules: FormRules = {
  columnType: [{ required: true, message: "请输入列类型", trigger: "blur" }],
  standardName: [
    { required: true, message: "请输入标准列名", trigger: "blur" }
  ],
  sortOrder: [{ required: true, message: "请输入排序序号", trigger: "blur" }],
  enabled: [{ required: true, message: "请选择是否启用", trigger: "blur" }],
  description: [{ required: true, message: "请输入描述", trigger: "blur" }]
};

// 新增国家
const close = () => {
  countryFormRef.value?.resetFields();
  countryFormRef.value?.clearValidate();
};
const isEdit = computed(() => !!countryForm.value?.id);
const submitLoad = ref(false);
const submitCountry = async () => {
  countryFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        submitLoad.value = true;
        const { columnType, ...rset } = countryForm.value;
        if (isEdit.value) {
          await updateColumnStandards(rset);
        } else {
          await createColumnStandards(countryForm.value);
        }
        ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
        dialogVisible.value = false;
        fetchCountries();
      } finally {
        submitLoad.value = false;
      }
    }
  });
};

const deleteCountry = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定删除标准列【${row.standardName}】吗？`,
      "删除确认",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await deleteColumnwStandards(row.id);
    ElMessage.success("删除成功");
    fetchCountries();
  } catch (error) {
    ElMessage.info("已取消删除");
  }
};

const editStandardColumn = async (row: any) => {
  const { id, standardName, columnType, description, sortOrder, enabled } = row;
  countryForm.value = {
    id,
    standardName,
    columnType,
    description,
    sortOrder,
    enabled
  };
  dialogVisible.value = true;
};
onMounted(() => {
  fetchCountries();
});
</script>

<style scoped>
.admin-countries {
  padding: 20px;
  background-color: #fff;
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
.header h2 {
  font-size: 20px;
  font-weight: bold;
}
</style>
